package org.yunai.yfserver.message.schedule;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.yunai.yfserver.common.LoggerFactory;

/**
 * 通过cron表达式建立的定时消息基类
 * User: yunai
 * Date: 13-5-24
 * Time: 下午8:21
 */
public abstract class ScheduledCronMessage extends ScheduledMessage {

    private Logger LOGGER = LoggerFactory.getLogger(LoggerFactory.Logger.schedule, ScheduledCronMessage.class);

    /**
     * cron表达式
     */
    private final String cron;
    /**
     * Quartz Scheduler
     */
    private Scheduler scheduler;
    /**
     * 任务KEY
     */
    private JobKey jobKey;

    protected ScheduledCronMessage(String cron) {
        super(0L);
        this.cron = cron;
    }

    @Override
    public synchronized void execute() {
        if (isCanceled()) {
            LOGGER.error("[execute] [msg:{} isCanceled] [cron:{}].", getClass(), cron);
            return;
        }
        LOGGER.info("[execute] [msg:{}] [cron:{}].", getClass(), cron);
        super.setState(STATE_EXECUTING);
        executeImpl();
        super.setState(STATE_DONE);
    }

    public abstract void executeImpl();

    @Override
    public synchronized void cancel() {
        try {
            scheduler.deleteJob(jobKey);
        } catch (SchedulerException e) {
            LOGGER.error("[cancel] [msg:{}] [cron:{}] [exception:{}].", getClass(), cron, ExceptionUtils.getStackTrace(e));
        }
        super.cancel();
    }

    public String getCron() {
        return cron;
    }

    public void setScheduler(Scheduler scheduler) {
        this.scheduler = scheduler;
    }

    public void setJobKey(JobKey jobKey) {
        this.jobKey = jobKey;
    }
}
